package com.wkbb.common.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.wkbb.common.handler.JsonUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 七牛云存储
 * 
 * @author root
 *
 */
@Slf4j
public class QiniuUtil {

	private static String access_key = "ctmObpxFWure2KOhcuVwiou2chdGTFOCRXe6IBjp";
	private static String secret_key =  "2fVfGGypKMRgD1s6gUNnDVCCIobSIlOHOnBexfj4";
	private static String space_name =  "righttimeedu";
	public static String qiniu_domain =  "https://qiniu.righttimeedu.com/";

	// 当前对象实例
	private static QiniuUtil QiniuUtil = new QiniuUtil();
	// 密钥配置
	private static Auth auth = Auth.create(access_key, secret_key);

	public String getToken(){
		return auth.uploadToken(space_name);
	}
	/**
	 * @Desc 获取当前对象实例
	 */
	public static QiniuUtil getInstance() {
		return QiniuUtil;
	}

	public String put(byte[] bytes,String fileName){
		log.info("QiniuUtil-put");
		//构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Region.region2());
		//...其他参数参考类注释
		UploadManager uploadManager = new UploadManager(cfg);
		String upToken = getToken();
		try {
			Response response = uploadManager.put(bytes, fileName, upToken);
			//解析上传成功的结果
			log.info("QiniuUtil-put:"+response.bodyString());
//			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			DefaultPutRet putRet = JsonUtil.jsonToClass(response.bodyString(), DefaultPutRet.class);
			if (putRet!=null){
				return qiniu_domain+fileName;
			}
		} catch (QiniuException ex) {
			Response r = ex.response;
			try {
				log.info("QiniuException:"+r.bodyString());
			} catch (QiniuException ex2) {
			}
		}
		return null;
	}

}
